package com.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

import com.service.UserService;

@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet {
	UserService us  = new UserService();
	HttpServletRequest request;
	HttpServletResponse response;
	protected void doGet(HttpServletRequest request, 
			HttpServletResponse response) throws ServletException, IOException {
		this.request=request;
		this.response=response;
		String me = request.getParameter("method");
		if (me.equals("logout")){
			this.logout();
		}
	}

	private void logout() throws ServletException, IOException {
		HttpSession session = request.getSession();
		session.removeAttribute("username");
		request.getRequestDispatcher("index.jsp").forward(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");
		request.setCharacterEncoding("utf-8");
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String cb = request.getParameter("cb");
		request.setAttribute("us",username);
		System.out.println("输入账号："+username);
		System.out.println("输入密码："+password);
		username=us.login(username,password);
		System.out.println(username);
		if(username!=null){
			//创建session 给session创建赋值
			request.getSession().setAttribute("username", username);
			if("cb".equals(cb)){
				Cookie cookie_username = new Cookie("username",username);
				Cookie cookie_password = new Cookie("password",password);
				//设置cookie的存活时间
				cookie_username.setMaxAge(1200);
				cookie_password.setMaxAge(1200);
				response.addCookie(cookie_username);
				response.addCookie(cookie_password);
			}
			//页面跳转
			request.getRequestDispatcher("login.jsp").forward(request, response);
		}else{
			request.setAttribute("errorMsg","账号或密码错误，请重新登录！！");
			request.getRequestDispatcher("index.jsp").forward(request, response);
		}
	}
}
